package com.steak.orm.datasource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public abstract class JdbcTemplate extends MyDataSource {

    protected static Connection connection;
    protected static PreparedStatement preparedStatement;
    protected ResultSet resultSet;

    //查询
    protected <T> List<T> executeQuery(String sql , RowMapper<T> rowMapper) throws Exception {
        preparedStatement = preparedStatement(sql);
        resultSet = preparedStatement.executeQuery();
        List<T> list = resultSet(resultSet, rowMapper);
        close();
        return list;
    }


    protected void execute(String sql){
        try {
            preparedStatement = preparedStatement(sql);
            preparedStatement.execute();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //close();
        }

    }

    //更新
    protected int executeUpdate(String sql) throws SQLException {
        preparedStatement = preparedStatement(sql);
        int i = preparedStatement.executeUpdate();
        close();
        return i;
    }

    //获取链接
    private Connection getConnection() throws SQLException {
        if (connection == null){
            connection = this.dataSource.getConnection();
        }
        return connection;
    }

    //预执行sql
    private PreparedStatement preparedStatement(String sql) throws SQLException {
        connection = getConnection();
        if (preparedStatement == null){
            preparedStatement = connection.prepareStatement(sql);
        }
        return preparedStatement;
    }

    //结果集
    private <T> List<T> resultSet(ResultSet resultSet , RowMapper<T> rowMapper) throws Exception {
        List<T> list = new ArrayList<>();
        while (resultSet.next()){
            list.add(rowMapper.mapRow(resultSet));
        }
        return list;
    }

    //关闭
    private void close(){
        try {
            if (connection != null) connection.close();
            if (preparedStatement != null) preparedStatement.close();
            if (this.resultSet != null) this.resultSet.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
